package com.hdoit.kylin.web.proposal.providers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

import org.springframework.util.StringUtils;

import com.hdoit.kylin.logical.studentManager.model.ReadDocument;
import com.hdoit.kylin.logical.studentManager.service.IReadDocumentService;
import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.message.ListItem;
import com.tennetcn.common.message.LoginModel;
import com.tennetcn.common.utils.CookieUtils;
import com.tennetcn.component.attribute.provider.ISingleOptionListProvider;
import com.tennetcn.component.web.SessionWebFactory;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;

public class DocumentProvider implements ISingleOptionListProvider<ListItem> {

	private List<ListItem> dataList;

	@Override
	public List<ListItem> getDataList(Object viewData) {
		List<ReadDocument> readDocuments= getAllReadDocuments();
		if(readDocuments==null||readDocuments.size()<=0){
			return null;
		}
		dataList=new ArrayList<ListItem>();
		ListItem listItem=null;
		for (ReadDocument readDocument : readDocuments) {
			listItem=new ListItem();
			listItem.setText(readDocument.getDocumentName());
			listItem.setValue(readDocument.getId());
			dataList.add(listItem);
		}
		return dataList;
	}

	private List<ReadDocument> getAllReadDocuments() {
		SessionWebFactory sessionWebFactory=CommonApplicationContextUtil.getCurrentContext().getBean(SessionWebFactory.class);
		IReadDocumentService readDocumentService=CommonApplicationContextUtil.getCurrentContext().getBean(IReadDocumentService.class);
		LoginModel loginModel=sessionWebFactory.getCurrentLogin();
		
		String loginId=loginModel.getLoginId();
		
		return readDocumentService.queryListByStudentId(loginId);
	}

	@Override
	public ListItem getSelectedItem(Object value, Object viewData) {
		if (StringUtils.isEmpty(value)) {
			try {
				PageContext pageContext = (PageContext) viewData;
				HttpServletRequest httpRequest = (HttpServletRequest) pageContext.getRequest();
				String readDocumentId = CookieUtils.getCookieValue(httpRequest, "readDocumentId", true);
				value = readDocumentId;
			} catch (Exception e) {
				return null;
			}
		}
		if (StringUtils.isEmpty(value)) {
			return null;
		}
		if (dataList == null) {
			return null;
		}
		final String readDocumentId = value.toString();
		return Enumerable.init(dataList).filter(d -> readDocumentId.equals(d.getValue())).first();
	}

}
